import qs from 'qs';

// const apiUrl = process.env.REACT_APP_API_URL

interface Config extends RequestInit {
  token?: string;
  data?: object;
}
export const Http = async <T>(
  endpoint: string,
  { data, token, headers, ...customConfig }: Config = {},
) => {
  const config = {
    method: 'GET',
    headers: {
      Authorization: token ? `Bearer ${token}` : '',
      'Content-Type': data ? 'application/json' : '',
    },
    ...customConfig,
  };
  if (config.method.toUpperCase() === 'GET') {
    endpoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }

  // ${apiUrl}/${endpoint}
  return window.fetch(endpoint, config).then(async response => {
    if (response.status === 401) {
      // 在这里退出登录
      // await auth.logout();
      window.location.reload();
      return Promise.reject({ messige: '请重新登陆！' });
    }
    const data: T = await response.json();
    if (response.ok) {
      return data;
    } else {
      return Promise.reject(data);
    }
  });
};
